<template>
  <div class="index">
    <div class="video">
      <div class="title">
        <span>{{ textBeyond(route.vodBlurb, 70) }}</span>
      </div>
      <div class="v" ref="videoContainer"></div>
    </div>
    <div class="list">
      <div class="index">
        <div class="item" v-for="(item,index) in videoList" :key="index" @click="toVideo(item)">
          <span> {{ Object.keys(item).toString().replace('[]', '') }} </span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {LocationQuery, useRoute} from 'vue-router'
import Artplayer from 'artplayer'
import {onMounted, ref, onBeforeUnmount} from 'vue'
import {textBeyond} from '@/utils'
import Hls from 'hls.js'

onMounted(async () => {
  await initVideo()
  if (videoContainer.value) {
    //@ts-ignore
    art = new Artplayer({
      ...videoOption.value,
      container: videoContainer.value
    })
  }
})

onBeforeUnmount(() => {
  if (art) {
    art.destroy()
    art = null
  }
})

const route: LocationQuery = useRoute().query
const videoContainer = ref<HTMLElement | any>(null)
const videoList = ref<Array<Object>>([])
const videoOption = ref<any>({
  url: '',
  autoSize: true,
  aspectRatio: true,
  fullscreen: true,
  poster: route.vodPic,
  autoMini: true,
  flip: true,
  setting: true,
  playbackRate: true,
  screenshot: true,
  hotkey: true,
  pip: true,
  lock: true,
  miniProgressBar: true,
  playsInline: true,
  gesture: true,
  fastForward: true,
  autoOrientation: true,
  airplay: true,
  customType: {
    //@ts-ignore
    m3u8: (video, url, art) => {
      if (Hls.isSupported()) {
        const hls = new Hls();

        // 在 level 加载后，过滤掉广告片段
        hls.on(Hls.Events.LEVEL_LOADED, (event, data) => {
          let segments = data.details.segments;

          // 根据名字/关键字/位置判断广告 ts
          data.details.segments = segments.filter(seg => {
            // seg.url 是完整 ts 链接，seg.sn 是片段序号
            if (seg.url.includes('ad') || seg.url.includes('advert')) {
              console.log('过滤广告 ts:', seg.url);
              return false; // 不要广告片段
            }
            // 比如跳过前 3 个片段（常见开头广告）
            if (seg.sn < 3) {
              console.log('过滤开头广告 ts:', seg.url);
              return false;
            }
            return true;
          });

          // 关键：修正 fragment 序号，避免后续卡死
          data.details.segments.forEach((seg, i) => {
            seg.sn = i;
          });

          console.log('过滤后片段数量:', data.details.segments.length);
        });

        hls.loadSource(url);
        hls.attachMedia(video);

        hls.on(Hls.Events.MANIFEST_PARSED, () => {
          if (videoOption.value.autoplay) video.play();
        });

        art.hls = hls;
      } else if (video.canPlayType('application/vnd.apple.mpegurl')) {
        video.src = url;
        video.addEventListener('loadedmetadata', () => {
          if (videoOption.value.autoplay) video.play();
        });
      } else {
        console.error('当前浏览器不支持 HLS');
      }
    }
  }
})
let art: Artplayer | null = null

const initVideo = async () => {
  // @ts-ignore
  videoList.value = route.vodPlayUrl.split('$$$')
      //@ts-ignore
      .flatMap(b =>
          //@ts-ignore
          b.split('#').map(item => {
            const [title, url] = item.split('$')
            return {[title]: url}
          })
      )
      //@ts-ignore
      .filter(obj => {
        const url = Object.values(obj)[0]
        //@ts-ignore
        return url && url.trim() !== ''
      })

  new Set(videoList.value)

  console.log(videoList.value)
  if (videoList.value.length > 0) {
    const firstObj = videoList.value[0]       // 拿到第一个对象
    const firstKey = Object.keys(firstObj)[0] // 拿到第一个 key
    //@ts-ignore
    videoOption.value.url = firstObj[firstKey] // 拿到对应的 url
    // @ts-ignore
    console.log(firstObj[firstKey])
  }
}

const toVideo = async (item: any) =>{
  const url = Object.values(item)[0] as string
  videoOption.value.url = url

  if (art) {
    art.switchUrl(url)
  }
}

console.log(route)
</script>

<style scoped lang="scss">
$width: 95%;
$min-width: 500px;

.width {
  width: $width;
  min-width: $min-width !important;
}

.index {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: row !important;
  justify-content: center;
  align-items: center;
  padding: 0 !important;
  background: var(--sub-theme);

  .video {
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: center;
    //border: 1px solid red;
    width: 70%;
    height: 100%;
    min-width: $min-width !important;

    .title {
      @extend .width;
      //border: 1px solid red;
      display: flex;
      justify-content: flex-start;
      align-items: center;
      margin-top: 30px;
      height: auto;
      background: var(--sub-theme);
      border-radius: 5px;
      padding: 5px;
      overflow: hidden;

      span {
        //border: 1px solid red;
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        font-size: 14px;
      }
    }

    .v {
      @extend .width;
      //border: 1px solid red;
      margin-top: 15px;
      height: 800px;

      * {
        //border: 1px solid red;
        margin: 0;
      }

      :deep(.art-video-player) {
        width: 100% !important;
      }
    }
  }

  .list {
    //border: 1px solid red;
    width: 30%;
    height: 100%;
    display: flex;
    //flex-direction: column;
    padding: 30px;
    flex-wrap: wrap;
    overflow: scroll;
    min-width: 300px;

    .index {
      //border: 1px solid red;
      background: var(--sub-theme);
      width: 100%;
      height: 100%;
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      overflow: scroll;
      //justify-content: space-between;
      align-items: flex-start;
      align-content: flex-start;
      justify-items: center;
      gap: 10px 0;
      flex: 1;


      .item {
        //border: 1px solid red;
        width: 90%;
        height: 50px;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 15px;
        margin: 5px;
        cursor: pointer;
        background: var(--theme);

        &:hover {
          border-radius: 10px;
          font-size: 18px;
        }
      }
    }
  }
}
</style>
